//
//  HJGroupTransferController.m
//  KaiChat
//
//  Created by lx on 2023/11/8.
//

#import "HJGroupTransferController.h"
#import "HJIM.h"
#import "HJGroupSelectMemberCell.h"
#import "HJSectionHeaderView.h"
#import "HJChatController.h"
#import "HJNavigationController.h"
#import "HJGroupMemberSearchController.h"
#import "QMUITextField.h"
#import "HJUIAlertController.h"
#import "HJSearchView.h"

@interface HJGroupTransferController ()<QMUITextFieldDelegate>

@property (nonatomic, strong) NSArray *datas;
@property (nonatomic, strong) NSArray *originalDatas;
@property (nonatomic, weak) QMUITextField *textField;
@property (nonatomic, strong) NSMutableArray *searchDatas;
@property (nonatomic, strong) NSIndexPath *lastIndexPath;
@property (nonatomic, weak) HJBarButton *doneButton;

@end

@implementation HJGroupTransferController

- (void)showInController:(UIViewController *)controller {
    HJNavigationController *navController = [[HJNavigationController alloc] initWithRootViewController:self];
    [controller presentViewController:navController animated:YES completion:nil];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    

    self.navigationBar.title = @"Select new founder";
    
    HJBarButton *doneButton = [HJBarButton barButtonWithTitle:@"Done" color:UIColor.tj_mainColor target:self action:@selector(didClickDoneButton)];
    doneButton.enabled = NO;
    [doneButton setTitleColor:UIColor.tj_mainColor forState:UIControlStateNormal];
    [doneButton setTitleColor:UIColor.tj_BEBDCAColor forState:UIControlStateDisabled];
    [self.navigationBar.contentView addSubview:doneButton];
    [doneButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(leftRightMargin);
        make.width.offset(40);
        make.centerY.offset(0);
        make.height.offset(40);
    }];
    _doneButton = doneButton;
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 60)];
    headerView.backgroundColor = UIColor.whiteColor;

    HJSearchView *searchView = [HJSearchView addToView:headerView];
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.top.offset(10);
        make.height.offset(40);
    }];
 
    QMUITextField *textField = searchView.textField;
    textField.placeholder = @"Search";
    textField.maximumTextLength = 30;
    textField.font = UIFontMake(14);
    textField.returnKeyType = UIReturnKeyDone;
    textField.delegate = self;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    _textField = textField;
    
    self.view.backgroundColor = UIColor.tj_F6F6F6Color;
    self.tableViewStyle = UITableViewStylePlain;
    self.tableView.tableHeaderView = headerView;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, TabbarSafeBottomMargin, 0);
    [self.tableView registerClass:HJGroupSelectMemberCell.class forCellReuseIdentifier:@"HJGroupSelectMemberCell"];
    [self.tableView registerClass:HJSectionHeaderView.class forHeaderFooterViewReuseIdentifier:@"HJSectionHeaderView"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.tableView.rowHeight = 60;
    self.tableView.backgroundColor = UIColor.tj_F6F6F6Color;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(KNavBarHight);
        make.left.right.bottom.offset(0);
    }];
    
    
    [HJIM.shareIM.groupManager queryGroupMemberListWithGroupId:self.groupId completion:^(NSArray<HJGroupMemberModel *> * _Nullable datas) {
    
        NSArray *memberModels = [HJIM.shareIM.groupManager groupMemberModelsSort:datas];
        self.originalDatas = memberModels;
        [self handleModels:memberModels];
    }];
    
 
}

- (void)handleModels:(NSArray *)models {
    
    NSMutableArray *administratorList = [NSMutableArray array];
    NSMutableArray *userList = [NSMutableArray array];
            
    for (HJGroupMemberModel *obj in models) {
        if (obj.role == 1) {
            continue;
        }
        if (obj.role == 2) {
            [administratorList addObject:obj];
        } else {
            [userList addObject:obj];
        }
    }
    
    self.datas = @[administratorList, userList];
    dispatch_async_main_queue(^{
        [self.tableView reloadData];
    });
}

- (void)textFieldDidChange:(QMUITextField *)textField {
    
    NSString *keyword = textField.text;

    if (isEmptyString(keyword)) {
        for (HJGroupMemberModel *obj in self.originalDatas) {
            obj.nicknameAttributedstring = nil;
        }
        [self.searchDatas removeAllObjects];
        [self handleModels:self.originalDatas];
        return;
    }
    
    [self.searchDatas removeAllObjects];
    for (HJGroupMemberModel *obj in self.originalDatas) {
        NSRange range = [obj.nickname rangeOfString:keyword options:NSCaseInsensitiveSearch];
        if (range.location != NSNotFound) {
            NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:obj.nickname];
            [attrStr addAttribute:NSForegroundColorAttributeName value:UIColor.tj_mainColor range:range];
            obj.nicknameAttributedstring = attrStr;
            [self.searchDatas addObject:obj];
        }
    }
    [self handleModels:self.searchDatas];
}

- (void)didClickDoneButton {
    
    HJGroupSelectMemberCell *lastCell = [self.tableView cellForRowAtIndexPath:_lastIndexPath];

    HJUIAlertController *alert = [HJUIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"By confirming the selection of %@ as a new foundervou willautomatically give up yourfounder status", lastCell.model.nickname] preferredStyle:HJUIAlertControllerStyleActionSheet];
    [alert addAction:[HJUIAlertAction actionWithTitle:@"OK" style:HJUIAlertActionStyleDestructive handler:^(HJUIAlertAction * _Nonnull action) {
        
        [HJHUD showLoadingInView:self.view];
        
        [HJIM.shareIM.groupManager transferGroupByGroupId:self.groupId userId:lastCell.model.userId completion:^(NSError * _Nullable error) {
            if (error) return;
            if (self.complete) {
                self.complete();
            }
            [self dismissToRootViewController:YES completion:nil];
        }];
    }]];
    [alert addAction:[HJUIAlertAction actionWithTitle:@"Cancel" style:HJUIAlertActionStyleCancel handler:nil]];
    [alert showInViewController:self];

}
 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *datas = self.datas[section];
    return [datas count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJGroupSelectMemberCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJGroupSelectMemberCell" forIndexPath:indexPath];
    HJGroupMemberModel *model = self.datas[indexPath.section][indexPath.row];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_lastIndexPath) {
        HJGroupSelectMemberCell *lastCell = [tableView cellForRowAtIndexPath:_lastIndexPath];
        lastCell.model.isSelect = NO;
        lastCell.model = lastCell.model;
    }
    
    self.doneButton.enabled = YES;
    HJGroupSelectMemberCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    HJGroupMemberModel *model = self.datas[indexPath.section][indexPath.row];
    model.isSelect = YES;
    cell.model = model;
    
    _lastIndexPath = indexPath;
}

 
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
     NSArray *sectionDatas = self.datas[section];
    return sectionDatas.count == 0 ? CGFLOAT_MIN : 20;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    NSArray *sectionDatas = self.datas[section];
    HJSectionHeaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"HJSectionHeaderView"];
    if (section == 0) {
        view.titleLabel.text = sectionDatas.count == 0 ? nil : [NSString stringWithFormat:@"Founder, Administrator (%ld people）", sectionDatas.count];
    } else {
        view.titleLabel.text = sectionDatas.count == 0 ? nil : [NSString stringWithFormat:@"Group Members (%ld people) ", sectionDatas.count];
    }
    view.contentView.backgroundColor = UIColor.tj_F6F6F6Color;
    view.backgroundColor = UIColor.tj_F6F6F6Color;
    view.titleLabel.textColor = UIColor.tj_BEBDCAColor;
    view.titleLabel.font = UIFontMake(12);
    return view;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = UIColor.clearColor;
    return view;
}

- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationFullScreen;
}

- (NSMutableArray *)searchDatas {
    if (!_searchDatas) {
        _searchDatas = [NSMutableArray array];
    }
    return _searchDatas;
}

- (void)dealloc {
    TJLog(@"%s", __func__);
}

@end
